package cn.com.blueInfo.security.service;

import cn.com.blueInfo.utils.result.ResultInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理未认证请求
 */
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        // 设置响应格式为 JSON
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // 设置状态码（401 未认证 / 403 权限不足，根据实际场景选择）
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        ResultInfo<Object> result = new ResultInfo<>();
        result.setResult(false);
        result.setMessage(authException.getMessage());
        result.setError("Unauthorized");
        result.setCode(HttpServletResponse.SC_UNAUTHORIZED);

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(response.getOutputStream(), result);
    }
}
